package com.xuliugen.ossdemo.qcloudclient;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Properties;

/**
 * 自己定义的七牛文件上传Client
 * Created by xuliugen on 16/5/22.
 */
public class QiniuClient {

    private static Properties props = new Properties();
    private static Logger log = LoggerFactory.getLogger(QiniuClient.class);

    static {
        try {
            props.load(QiniuClient.class.getResourceAsStream("/qiniu.properties"));
        } catch (IOException e) {
            log.error("加载配置文件失败", e);
        }
    }

    static String accessKey = props.getProperty("accessKey");
    static String secretKey = props.getProperty("secretKey");
    static String bucket = props.getProperty("bucket");

    static Auth auth = Auth.create(accessKey, secretKey);

    /**
     * 上传文件到七牛服务器(断点上传)
     * @param key  文件名
     * @param data 文件内容  byte[]
     * @throws Exception
     */
    public static void uploadFile(byte[] data, String key) throws Exception {
        //同名文件覆盖操作、只能上传指定key的文件可以可通过此方法获取token
        String token = auth.uploadToken(bucket, key);
        UploadManager uploadManager = new UploadManager();
        //上传数据
        uploadManager.put(data, key, token);
    }

    /**
     * 从七牛服务器下载文件（获取下载地址）
     * @param key 文件名
     * @throws Exception
     */
    public static String downloadFile(String key) throws Exception {
        return auth.privateDownloadUrl(key, 3600 * 24);
    }

    /**
     * 从七牛服务器删除文件
     * @param key 文件名
     */
    public static void delFile(String key) throws Exception {
        BucketManager bucketManager = new BucketManager(auth);
        bucketManager.delete(bucket, key);
    }
}